
__tags__ = "maya, references, find, ascii, ma"

class FindMayaReferences(ni.Node):
    ''' Find all references to a Maya file, given a .ma file '''
    mafile = ni.File()
    references = ni.List(itemtype=ni.File(), depends=[mafile])
    
    def find_filepaths(self, string):
        ''' Finds lines that starts with "file -r",
            and gets the last string in those lines, which should be the reference path.
        '''
        path_pattern = re.compile("(file -r .+)")
        
        filepaths = []
        for match in path_pattern.findall(string):
            parts = match.split("\"")
            path = parts[-2]
            if path in filepaths:
                continue
            filepaths.append(parts[-2])
        
        return filepaths
    
    def compute_references(self):
        if self.mafile is None: return
        if not os.path.exists(self.mafile):
            raise ValueError("Given Maya ASCII file does not exist: "+ str(self.mafile))
        
        with open(self.mafile) as file_handle:
            references = self.find_filepaths(file_handle.read())
            
        return references
    